import requests
import base64
import random
import math
import execjs
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

# 获取歌曲的地址
url = "https://music.163.com/weapi/cloudsearch/get/web?csrf_token=2d7ab82ef76bf04aa42109aa54ee915d"

data = r'{"hlpretag":"<span class=\"s-fc7\">","hlposttag":"</span>","s":"赵雷","type":"1","offset":"0","total":"true","limit":"30","csrf_token":"2d7ab82ef76bf04aa42109aa54ee915d"}'

# 加密方法
def aes_encrypt(d, g):

    cipher = AES.new(g.encode("utf-8"), AES.MODE_CBC, iv="0102030405060708".encode("utf-8"))
    pad_data = pad(d.encode("utf-8"), 16)  # 填充，确保每个数据块都是16个字节
    cipher_text = cipher.encrypt(pad_data)

    return base64.b64encode(cipher_text).decode("utf-8")


# 获取指定个数的随机字符串
def get_random_str(num):
    # 100
    s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    c = ""

    for i in range(num):
        r = random.random() * len(s)
        index = math.floor(r)  # [0, 99)
        c += s[index]

    return c


random_str = get_random_str(16)

params = aes_encrypt(aes_encrypt(data, "0CoJUm6Qyw8W8jud"), random_str)


"""
获取encseckey
"""
with open("rsa.js", "r", encoding="utf-8") as fp:
    js = fp.read()


cxt = execjs.compile(js)
e = "010001"
f = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
enc_sec_key = cxt.call("rsa_encrypt", random_str, e, f)

params = {
    "params": params,
    "encSecKey": enc_sec_key
}

headers = {
    "content-type": "application/x-www-form-urlencoded",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
    "cookie": "NMTID=00ORTiMkbVrgacIM0WXrro8ALZGRDoAAAGQl7xJ3w; _iuqxldmzr_=32; _ntes_nnid=9e92cbb7787a44b3cd7bc414f5b4d502,1720532619308; _ntes_nuid=9e92cbb7787a44b3cd7bc414f5b4d502; WM_TID=b4CAsMbe7YdEQABAAAfCQdJ%2BiuBySBR5; WEVNSM=1.0.0; WNMCID=ghzsmm.1720532620962.01.0; sDeviceId=YD-VewOx8uTe0xFQlFEEQfXVMMuy7AniKna; ntes_utid=tid._.tYMllcewls1FB1BBQBfCFIcv36EmyCpJ._.0; __snaker__id=Pknad9qNoMo02FmU; nts_mail_user=liu_2276224279@163.com:-1:1; NTES_P_UTID=516oSLK41r6yo26ZBoTVJZDePdCsLhIG|1723616765; __remember_me=true; ntes_kaola_ad=1; gdxidpyhxdE=Iq1pxL65ch1RMIh%2Bc8HXI48gbgD50RSJ6oEdE3dRUdk4Z14BY%2Fd2xNLopuAW7lTJahNiaI9s59mYJ8l%2BKsq7HB6vzZOr5jDzu796neTJHPMuGecjduOUVDCySMtx%5Cx7tXoE24RY1nDZOjT%2Bu9OZd7TKBBtx2ISk5z%2FGAOHEaGkapMgiJ%3A1728285155976; P_INFO=15973194541|1728284356|1|music|00&99|null&null&null#hun&null#10#0|&0|null|15973194541; MUSIC_U=00EA6FCED594CE4292F135D93FA2DFF1ACFFF76A48DB35CBF022AC2F0EBE963EE9E8B7BA9C9B5CACA7706490D6A46109D4EC6FD65D57766C1B2A97AE8DC8AC00B784D4A7A44C59DEE895EC47318439B4557F53DA4DC632F7C1CE9F8A5F01233475860F04DC63C0B073E305EBE6D7AA688D6358243E7DD45BB8F0BF1672AA9EC1F2B9CCA941AFB719A12235A73D1ACC343FA0E1381942C218C03595D74A09C46395892791B798BD32066102D8DDC02F0E69C9C51E2B7278995865C5F352A85CB5517837EC7D02AD5E6A4C17A588281F4D33D06C1A4D1A7C7D5F96CF548AF684C4F27F4C74ABF78EB63080E0E46E00994C29BE0101323EB0C5B823AA19BBF0FEA198619F9FF1C18740FF4884DD78B4ED2F281AD6C03A24DDAF741D187AC8D5B31A04551DEE8CF8C5AF3473A67340D72F28509F6957075104D00C0A607A2E373F6FBE71265F0BC9A06A41905065AD22D5FCF6DFC4BE2B941365D1B51371812605B0D9; __csrf=2d7ab82ef76bf04aa42109aa54ee915d; WM_NI=inv2foBoP%2F8UebjRnl3ms7JUYsewnhqS31j5%2FTVBQXSCyEcGgcNkQxLMQmnM6uNrqY6S%2FJPoIr0M8Z4N6xUgY2fQeb4%2F6ZbIo%2FykNcqf5oNdktRZ1nyOaj%2BtkFb3pRHZQU0%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eed2f447f798fbaace46adef8bb2d54b869a8aacc75098ee96d7ef73829caebbe92af0fea7c3b92aabb2bad3e56582b1a0d0bb5fa7bea6b3ed68f1b3bdd8c95f9badab98ed64b38dfdd2e93fed8c9aa3d454919db7a6e24da5bd828cd47490939f8eed47f6ab8293f453f68de1abd3658bae00aebb52f892fa99d86d9beeaab2e86af8f1fabbe143adf1b78ccd69b3bafb90cd70a9ac9ebbb466bb91af8baa80a99aaed4f35a8c869fb6b337e2a3; JSESSIONID-WYYY=nG3c4ugG0SjDDWRrMANjA7sAmjl9JFsJdFs1ic1HyZNNB0uF8sZHuJOoEnc1U4cD8055zRwGxr%2BHo2PV%2BCBWofIEaD7SfNCVa8p1VJo9U5n%2FEv1Wqu06P429XqGDsVSNOFoKmRFz5kkbAjbCNkPDxvPA%2BMWN0u3gSVWxJEcCPRORRcdJ%3A1728392298763"
}
text = requests.post(url, data=params, headers=headers).text

# 获取所有的歌曲
songs = json.loads(text)["result"]["songs"]

for song in songs:
    music_name = song["name"]  # 音乐名称
    music_id = song["id"]

    # 获取音频地址的url
    url2 = "https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token=2d7ab82ef76bf04aa42109aa54ee915d"

    data2 = '{"ids":"['+ str(music_id)+']","level":"standard","encodeType":"aac","csrf_token":"2d7ab82ef76bf04aa42109aa54ee915d"}'
    enc_text = aes_encrypt(aes_encrypt(data2, "0CoJUm6Qyw8W8jud"), random_str)
    params = {
        "params": enc_text,
        "encSecKey": enc_sec_key
    }
    text2 = requests.post(url2, data=params, headers=headers).text

    # 音乐地址
    music_url = json.loads(text2)["data"][0]["url"]

    if music_url:
        print(f"-------正在下载，{music_name}")
        music_content = requests.get(music_url).content

        music_dir = "D:/projects/spider/day10逆向社保平台/music/" + music_name + ".mp3"
        with open(music_dir, "wb") as fp:
            fp.write(music_content)











